
import React, { useState, useEffect, useImperativeHandle, forwardRef } from 'react'
import { Modal, Form, Input, Button, message, Spin } from 'antd';
import Funs from '@/utils/Funs'
import API from '@/api/api'
import './index.scss';

function VerifyBox(props, ref) {

    const [load, setLoad] = useState(false)
    const [status, setStatus] = useState(false)
    const [verifyImg, setVerifyImg] = useState()
    const [verifyKey, setVerifyKey] = useState()
    const [form] = Form.useForm();

    useImperativeHandle(ref, () => {
        return { openModal, cancelModal }
    })

    const openModal = () => {
        setStatus(true)
        getVerify()
    }

    const cancelModal = () => {
        setStatus(false)
    }

    const getVerify = async () => {
        let res = await API.getVerify()
        if (res) {
            setVerifyImg(res.img)
            setVerifyKey(res.key)
        }
    }

    const onFinish = async (values) => {
        const fileds = await form.validateFields(['captcha'])

        if (!fileds.captcha) {
            message.warning('请输入图形验证码')
            return false
        }
        props.send(fileds.captcha, verifyKey)
    };


    return (
        <Modal className="verify-code" visible={status} onCancel={cancelModal} footer={null}>
            {
                !load ? null :
                    <div className="load-mark">
                        <Spin />
                    </div>
            }
            <Form className="verify-form" form={form} onFinish={onFinish}>
                <Form.Item name="captcha">
                    <Input placeholder="输入验证码" suffix={<img className="verify-img" onClick={getVerify} src={verifyImg} />} />
                </Form.Item>
                <Form.Item>
                    <Button type="primary" htmlType="submit">确定</Button>
                </Form.Item>
            </Form>
        </Modal>
    )
}

export default forwardRef(VerifyBox)